package net.homeip.mmhg.game;

import java.util.Arrays;
import java.util.Random;

import net.homeip.mmhg.domain.Task;

import org.springframework.stereotype.Service;

/**
 * Select random task from vacant tasks. 
 *
 * @author ilya gerasimov
 */
@Service
public class RandomDispatcher implements Dispatcher {

	private Random random = new Random();
	
	@Override
	public Task obtainTask(GameContext context, Position position) {
		Task[] vacant = selectVacant(context, position);
		if ( (vacant != null) && (vacant.length != 0) ) {
			return vacant[random.nextInt(vacant.length)];
		} else {
			return null;
		}
	}
	
	private Task[] selectVacant(GameContext context, Position position) {
		Task[] vacant = new Task[context.getTasks().size()];
		int current = 0, currentPriority = 0;
		int vacantThreshold = context.getPositions().size();
		for (Task task : context.getTasks()) {
			if (!task.canBeObtained(context.getOwns(task).size())
					|| position.getObtainedTasks().containsKey(task.getId())) {
				continue;
			}
			if (currentPriority < task.getPriority()) {
				currentPriority = task.getPriority();
				current = 0;
				vacantThreshold = context.getOwns(task).size();
				vacant[current++] = task;
			} else if (currentPriority == task.getPriority()) {
				if (context.getOwns(task).size() < vacantThreshold) {
					vacantThreshold = context.getOwns(task).size();
					current = 0;
					vacant[current++] = task;
				} else if (context.getOwns(task).size() == vacantThreshold) {
					vacant[current++] = task;
				}
			}
		}
		return Arrays.copyOf(vacant, current);
	}
}
